<template>
  <!-- 这里的代码尽量保持原有暑期作业键盘的逻辑，现在虽然没有使用了，以后保不齐要用，删了就自求多福了-->
  <transition name="fade">
    <!-- 普通键盘类型(暑期作业的键盘已经停用) -->
    <div
      v-if="boardChoice.tabs.length < 1"
      v-show="show"
      key="keypad"
      class="linpeng-key-board-div"
      :style="boardStyle"
      :class="[
        {
          &quot;phone&quot;:vthis&&vthis.rootdata.screenflag===2,
          &quot;pad&quot;:vthis&&vthis.rootdata.screenflag===1&&vthis.rootdata.bookflag===0,
          &quot;book_pad&quot;:vthis&&vthis.rootdata.screenflag===1&&vthis.rootdata.bookflag===1}
      ]"
    >
      <div class="aimtooldiv clear-fix">
        <p
          v-show="pinyinstr"
          class="k-candidate"
        >
          {{ pinyinstr }}
        </p>
        <p
          v-show="(boardType !== 'handwriter' && !pinyinstr) || (boardType === 'handwriter' && !handWriterStr)"
          class="input-type-choice"
        >
          <!--键盘-->
          <span
            v-if="fillMode !== 'tian'"
            class="keyboard"
            :class="{active: boardType !== 'handwriter'}"
            @click="keyBoard"
          />
          <!--手写-->
          <span
            class="writeboard"
            :class="{active: boardType === 'handwriter'}"
            @click="crossWalkApplay(1)"
          />
          <!--手绘-->
          <span
            v-if="fillMode === 'subjective' && mobile"
            class="HandPaintImg"
            @click="crossWalkApplay(2)"
          />
          <!--图片-->
          <span
            v-if="fillMode === 'subjective'"
            class="choosePhoto"
            @click="crossWalkApplay(3)"
          />
          <!--音频-->
          <span
            v-if="fillMode === 'subjective'"
            class="audio"
            @click="openRecoder()"
          />
        </p>
        <div
          v-show="!candidateShow"
          class="hiddth-scroll fl"
        >
          <div
            class="aimresultdiv"
            :style="{overflowX: mobile ? 'auto' : 'hidden'}"
            style="overflow-y: hidden"
            :class="{mobile: mobile}"
          >
            <ul
              class="result clear-fix"
              :class="{mobile: mobile}"
              :style="cp_result"
            >
              <li
                v-for="(value,key) in cp_candidate"
                :key="key"
                class="fl result-li"
                :data-idx="(key+1)"
                :style="cp_result_li"
                @click="choicehz(value)"
              >
                <span class="result-span">{{ value }}</span>
              </li>
            </ul>
          </div>
        </div>
        <div
          v-if="cp_candidate.length <= 10 && !candidateShow"
          class="aimclosediv fr"
          @click.stop="closeclick"
        />
        <div
          v-if="cp_candidate.length > 10 && !candidateShow"
          class="aimmorediv fr"
          @click.stop="moreclick"
        />

        <recorder
          v-if="recorder"
          ref="recorder"
          :is-production="isProduction"
          :recording-duration="120"
        />

        <platform-resource-selector
          v-show="false"
          v-if="rouceImg"
          ref="resourceImg"
          type="image"
          :upload-url="'/api/res-file/upload/singleFile'"
          :succ="sourceSelectorSuc"
          multiple
          :max="2"
          :max-size="5*1024"
          :throw-exception="getException"
        />
      </div>

      <!--公式输入框-->
      <div
        v-show="formulaReg.show"
      >
        <div
          class="formula-reg formula"
        >
          <formula-view
            :data="formulaReg.data"
            @emit-click="formulaClick"
          />
          <span
            class="formula-btn"
            :class="{ disabled: formulaDisabled }"
            @click="confirmFormula"
          >确定</span>
        </div>
      </div>
      <div
        ref="mirror"
        class="formula-mirror formula"
      >
        <formula-view
          :key="cp_mirror.name"
          :data="cp_mirror"
        />
      </div>
      <keep-alive>
        <component
          :is="cp_board.compName"
          :board-data="cp_board"
          :board-type="boardType"
          :board-model="boardModel"
          :disable-btn="disableBtnMap"
          :payload="cp_payload"
          :mobile="mobile"
          @keep-press="keepPress"
          @clearT="clearTimer"
          @btn-click="btnClick"
          @handWriterCb="handWriterCb"
          @on-model="onModel"
        />
      </keep-alive>
      <div
        v-if="candidateShow"
        class="cp_candidate_wrapper"
      >
        <component
          :is="TheCandidate"
          :candidate="cp_candidate"
          :disable-btn="disableBtnMap"
          @keep-press="keepPress"
          @btn-click="btnClick"
        />
      </div>
    </div>
    <!-- 选择填空的键盘类型 (属性作业特有的键盘类型) -->
    <div
      v-else
      v-show="show"
      key="choice"
      class="im-choice"
    >
      <div
        class="im-close"
        @click.stop="closeclick"
      >
        <span />
      </div>
      <keep-alive>
        <component
          :is="cp_board.compName"
          :board-choice="boardChoice"
          @keep-press="keepPress"
          @btn-click="btnClick"
        />
      </keep-alive>
    </div>
  </transition>
</template>

<script>
/* eslint-disable no-undef,no-lone-blocks */
import html2canvas from 'html2canvas';
import comp from './view';
import Bus from './view/emitBus';
import keysTextJson from './json/keystext.json';
import pyinput from './json/pyinput.json';
import spell from './json/spell.json';
import { $debounce, browerEnv, _onlyNumber } from './view/utils';
import FormulaView from './view/FormulaView';
import syllable from './json/syllable';
import PlatformResourceSelector from '../../platformResourceSelector/resourceSelector/resourceSelector';

export default {
    name: 'Keyboard',
    data () {
        return {
            vthis: '', // 组件对象this
            show: false,
            recorder: false,
            rouceImg: false,
            isProduction: process.env.NODE_ENV === 'production', // 生产环境
            keypadjson: [],
            type: 0,
            i: 0,
            enterflag: 0, // 换行和下一空标记
            maxlength: '',
            closeimfun: function () {
            },
            inputarray: [],
            pinyinflag: 1, // 拼音输入标记
            capflag: 0, // 大小写标记
            numflag: 0, // 通用键盘的数字标记
            hanziarray: [], // 候选汉字的汉字
            pyinputjson: {}, // 拼音字库
            TheCandidate: 'TheCandidate',

            isUpper: false, // 英文字符是否大写
            prevBoardType: [], // 切换过的键盘类型堆栈
            boardType: '', // 键盘类型 拼音/手写/竖式/公式/组合
            symbolType: 'math', // 符号类型
            nextId: '', // 下一个跳转ID
            symbols: [], // 匹配的符号组
            candidate: '', // 候选的汉字
            pinyinstr: '', // 候选拼音
            boardModel: 'chinese', // 键盘模式 text:英文 chinese：中文
            candidateShow: false, // 中文输入法时，是否显示选词界面
            boardChoice: {
                tabs: [],
                mode: 'single',
            }, // 选择填空,

            pattern: 'js', // 输入模式
            fullFirst: true, // 首个符号组是否充满默认位置
            jsCallbacks: {}, // 纯输入模式时的回调函数
            el: '', // 键盘的挂载节点
            timer: null,
            fillMode: '', // 填空题空的题型  'objective'客观  'subjective'主观  'special' 特殊填空区 'tian'田字格
            defaultMode: 0, // 默认打开模式  0键盘输入  1手写识别  2手写笔迹
            mobile: browerEnv().android || browerEnv().ios, // 是否是移动端环境
            handWriterStr: '', // 手写板传来的待选词
            disableBtnMap: [], // 禁用的键盘按钮
            formulaReg: {
                show: false, // 显示公式输入区
                data: {
                    name: '',
                    value: {
                        mixed: [],
                        up: [],
                        down: [],
                    },
                },
                text: '',
            },
            formulaName: ['fraction', 'sqrt2', 'sqrt3', 'aimsup', 'aimsub', 'loop'], // 公式种类
            boardStyle: {
                fontSize: '12px',
            },
            resize: $debounce(this.calcFontSize, 100, false),
        };
    },
    // eslint-disable-next-line vue/order-in-components
    components: { PlatformResourceSelector, FormulaView, ...comp },
    computed: {
        cp_board () { // 计算键盘类型
            let { boardType, symbols, prevBoardType } = this;
            let obj = keysTextJson[boardType] || {};
            let keysText = obj.data;
            let tabs = [];
            return {
                compName: obj.model,
                keysText,
                symbols,
                prevBoardType: prevBoardType[prevBoardType.length - 1],
                tabs,
            };
        },
        /* 匹配拼音 */
        cp_candidate () {
            let { boardType } = this;
            if (boardType === 'spell') {
                return (spell[this.pinyinstr] || '');
            } else if (['combo', 'chinese', 'public'].includes(boardType)) {
                return (pyinput[this.pinyinstr] || '');
            } else if (['handwriter'].includes(boardType)) {
                return this.handWriterStr;
            } else if (['syllable'].includes(boardType)) {
                let obj = {};
                Object.values(syllable).forEach(item => {
                    if (!Array.isArray(item)) {
                        Object.assign(obj, item);
                    }
                });
                return (obj[this.pinyinstr] || '');
            }
            return '';
        },
        cp_result () {
            return {
                width: 10 * this.cp_candidate.length + '%',
            };
        },
        cp_result_li () {
            return {
                width: 100 / (this.cp_candidate.length || 1) + '%',
            };
        },
        cp_payload () {
            return {
                mType: (this.vthis.testdata || {}).mtype,
                fullFirst: this.fullFirst,
                pattern: this.pattern,
            };
        },
        cp_mirror: function () {
            let data = this.formulaReg.data,
                up = data.value.up.filter(m => m.name !== 'cursor'),
                down = data.value.down.filter(m => m.name !== 'cursor'),
                mixed = data.value.mixed.filter(m => m.name !== 'cursor'),
                valup = '',
                valMixed = '',
                valdown = '';
            up.forEach(m => (valup += m.value));
            down.forEach(m => (valdown += m.value));
            mixed.forEach(m => (valMixed += m.value));
            return {
                name: data.name,
                value: { up, down, mixed },
                data: {
                    up: valup,
                    down: valdown,
                    mixed: valMixed,
                },
            };
        },
        formulaDisabled () {
            let data = this.formulaReg.data,
                upL = data.value.up.filter(a => a.name !== 'cursor').length,
                downL = data.value.down.filter(a => a.name !== 'cursor').length;
            if (['sqrt2', 'loop'].includes(data.name)) {
                return !downL;
            } else if (['aimsup', 'aimsub', 'fraction'].includes(data.name)) {
                return !upL || !downL;
            }
            return false;
        },
    },
    watch: {
        /* 监听输入值变化 */
        'inputarray' (val, old) {
            val === old || this.removecursor(old);
        },
        show () {
            this.$nextTick(this.calcFontSize);
        },
    },
    mounted () {
        let self = this;
        document.body.appendChild(this.$refs.mirror);
        if (window.icomLindadayo) {
            /* 录音插件 */
            window.icomLindadayo.utils.getScript([
                window.icomLindadayo.env.baseUrl + '/../../recorder/libs/recorder.js',
                window.icomLindadayo.env.baseUrl + '/../../recorder/1.0.1/recorder.umd.min.js',
            ], (e) => {
                self.recorder = true;
            }, 1);
            /* 上传图片插件 */
            window.icomLindadayo.utils.getScript([
                window.icomLindadayo.env.baseUrl + '/../../platformResourceSelector/1.0.0/platformResourceSelector.umd.min.js',
            ], (e) => {
                self.rouceImg = true;
            }, 1);
        }
        this.$nextTick(this.calcFontSize);
        window.addEventListener('resize', this.resize);
    },
    methods: {
        // openMode:0,键盘，1，手写，2，手绘，3，选图
        crossWalkApplay (openMode) { // 手写
            let p = {
                1: 'handwriter',
                2: 'HandPaintImg',
                3: 'choosePhoto',
            }[openMode];
            if (this.beforeChangeType(p) === false) {
                return;
            }

            this.hideFormula();
            console.log('openMode: ', openMode, 'fillMode: ', this.fillMode);
            if (this.mobile) {
                try {
                    window.qti_maidian && window.qti_maidian('02201003');
                    if (window.navigator.userAgent.match(/CrossWalk/i)) {
                        console.log('start PenRecog mode: ' + openMode);
                        var disableNext = ~this.disableBtnMap.indexOf('next') ? 1 : 0;
                        if (this.fillMode) {
                            let showMode = this.fillMode === 'subjective' ? {
                                handWrite: 1,
                                handPaint: 1,
                                choosePhoto: 1,
                                recordAudio: 1,
                                disableNext: disableNext,
                            } : {
                                handWrite: 1,
                                handPaint: 0,
                                choosePhoto: 0,
                                disableNext: disableNext,
                            };
                            if (this.fillMode === 'tian') {
                                showMode = {
                                    handWrite: 1,
                                    handPaint: 0,
                                    choosePhoto: 0,
                                    recordAudio: 0,
                                    keyboard: 0,
                                    disableNext: disableNext,
                                };
                                this.closeclick();
                            }
                            window.cordova.exec(() => {
                                console.log(1);
                            }, () => {
                                console.log(33);
                            }, 'PenRecog', 'show', [openMode, JSON.stringify(showMode)]);
                        } else {
                            window.cordova.exec(null, null, 'PenRecog', 'show', [openMode, JSON.stringify({
                                handWrite: 1,
                                handPaint: 0,
                                choosePhoto: 0,
                                disableNext: disableNext,
                            })]);
                        }
                    }
                } catch (error) {
                    console.log(error);
                }
            } else {
                this.handWriterStr = '';
                if (openMode === 1) {
                    if (this.boardType === 'handwriter') return false;
                    this.prevBoardType.push(this.boardType);
                    this.boardType = 'handwriter';
                } else if (openMode === 3) { // 选图
                    this.$refs.resourceImg.uploadSource();
                }
            }
            openMode !== 3 && typeof this.jsCallbacks.change === 'function' && this.jsCallbacks.change({
                type: 'openMode',
                data: openMode,
            });
        },
        /* 启用录音插件 */
        openRecoder () {
            if (this.beforeChangeType('audio') === false) {
                return;
            }
            this.hideFormula();
            let self = this;
            self.$refs.recorder.record({
                succCallback: info => {
                    console.log('成功回调', info);
                    if (self.pattern === 'js') {
                        self.emitChange({
                            type: 'recorder',
                            url: info,
                        });
                    }
                },
                errorCallback: info => {
                    this.$toast(info.msg);
                },
            });
        },
        // 点击键盘输入
        keyBoard () {
            let t = this.prevBoardType.slice(-1)[0] || this.boardType;
            if (this.beforeChangeType(t) === false) {
                return;
            }
            if (!this.mobile && this.boardType === 'handwriter') this.boardType = this.prevBoardType.pop();
        },
        // 手写版搜索出词汇后的回调函数
        handWriterCb (words, pre) {
            if (!this.handWriterStr && pre === 'click_word') return false;
            if (this.pattern === 'js') {
                typeof this.jsCallbacks.change === 'function' && this.jsCallbacks.change(`${pre}${words && words.split('')[0]}`);
                this.handWriterStr = words;
            }
        },
        // 拼音输入选中汉字
        choicehz: function (hz) {
            if (this.boardType === 'syllable' || this.boardType === 'handwriter') {
                hz = `click_word${hz}`;
            }
            this.getinputstr(hz);
            this.handWriterStr = '';
            this.pinyinstr = '';
            this.hanziarray = [];
            this.candidateShow = false;
        },
        clearTimer () {
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        /* 点击键盘 */
        btnClick (e, { expect, text, type, isUpper = false, view }) {
            if (this.mobile) {
                let { type } = e || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            } else {
                let { type } = e || window.event;
                if (type.match(/touch/g)) {
                    return false;
                }
            }
            console.log(expect, text, type, view);
            let { boardType, boardModel } = this;
            if (this.mobile) {
                let { type } = e || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            if (this.candidateShow) {
                if (expect === 'goback') {
                    this.candidateShow = false;
                } else if (expect === 'next') {
                    ['next'].includes(expect) && (text = 'next');
                    this.getinputstr(text);
                    text = '';
                    this.pinyinstr = '';
                    this.candidateShow = false;
                } else if (expect === 'delete') {
                    this.clearTimer();
                    if (this.pinyinstr) {
                        this.pinyinstr = this.pinyinstr.slice(0, -1);
                        if (this.pinyinstr === '') {
                            this.candidateShow = false;
                        }
                    } else {
                        this.candidateShow = false;
                        this.getinputstr('delete');
                    }
                } else {
                    this.choicehz(text);
                }
                return false;
            }
            // return false
            /* 特殊拼音 */
            if (boardType === 'spell') {
                if (expect === 'spell') {
                    this.pinyinstr = text;
                    return;
                } else {
                    this.pinyinstr = '';
                }
            } else if (boardType === 'syllable') { // 拼音音节键盘
                if (this.pinyinstr) {
                    if (expect === 'delete') {
                        this.pinyinstr = '';
                    } else if (!['goback', 'next'].includes(expect)) {
                        this.choicehz(this.cp_candidate[0]);
                    }
                }
                if (expect === 'syllable') {
                    this.pinyinstr = text;
                    this.emitChange(`preselection_word${this.cp_candidate[0]}`);
                    return;
                } else {
                    this.pinyinstr = '';
                }
            } else if (boardType === 'handwriter') { // 手写键盘
                if (this.handWriterStr) {
                    if (['delete', 'goback', 'next'].includes(expect)) {
                        this.handWriterStr = '';
                    }
                }
            }
            /* 特殊按键 */
            if (this.formulaName.concat(['enter', 'space', 'σ^2']).includes(expect)) {
                if (boardType === 'number') { // 弹出公式输入框
                    this.showFormula(expect, text);
                    return;
                }
                this.getinputstr(expect);
                return;
            }
            if (boardType === 'number' && this.formulaReg.show) {
                if (['next', 'delete', 'goback'].includes(expect)) {
                    text = expect;
                }
                this.inputFormula(text);
                return;
            }

            if (expect === 'next' && (boardType !== 'combo' || boardType !== 'public')) {
                this.pinyinstr = '';
                if (['comboNumber'].includes(boardType) && boardModel !== 'chinese') {
                    ['next'].includes(expect) && (text = 'next');
                } else {
                    text = expect;
                }
                this.getinputstr(text);
                return;
            }
            /* 通用键盘 */
            if (boardType === 'combo' || boardType === 'chinese' || boardType === 'public') {
                if (expect === 'languageSwitch') {
                    this.pinyinstr = '';
                    this.boardModel = this.boardModel === 'text' ? 'chinese' : 'text';
                    this.beforeChangeType(boardType);
                    return;
                } else if (expect === 'chooseNumber') {
                    this.pinyinstr = '';
                    let t = boardType === 'public' ? 'number' : 'comboNumber';
                    if (this.beforeChangeType(t) === false) {
                        return;
                    }
                    this.prevBoardType.push(this.boardType);
                    this.boardType = t;
                    return;
                } else if (expect === 'caseSwitch') {
                    this.pinyinstr = '';
                    return;
                } else if (expect === 'syllable') { // 切换到拼音音节键盘
                    this.pinyinstr = '';
                    if (this.beforeChangeType('syllable') === false) {
                        return;
                    }
                    this.prevBoardType.push(this.boardType);
                    this.boardType = 'syllable';
                    return;
                } else if (['next'].includes(expect)) {
                    if (boardModel === 'text') {
                        text = 'next';
                    } else if (boardModel === 'chinese') {
                        this.pinyinstr = '';
                        this.getinputstr(expect);
                        return;
                    }
                }
            }
            /* 英文键盘 */
            if (boardType === 'letters') {
                if (expect === 'caseSwitch') {
                    return;
                }
            }

            /* 中文键盘 */
            if (boardModel === 'chinese' && (boardType === 'chinese' || boardType === 'combo' || boardType === 'public')) {
                if (expect === 'delete') {
                    if (this.pinyinstr) {
                        if (this.timer) {
                            clearInterval(this.timer);
                            this.timer = null;
                        }
                        this.pinyinstr = this.pinyinstr.slice(0, -1);
                    } else {
                        this.getinputstr('delete');
                    }
                } else if (expect === 'caseSwitch') {
                    this.pinyinstr = '';
                } else if (expect === 'switch') {
                    if (this.beforeChangeType('symbol') === false) {
                        return;
                    }
                    this.prevBoardType.push(this.boardType);
                    this.boardType = 'symbol';
                    this.pinyinstr = '';
                    return;
                } else if (expect === 'space') {
                    this.getinputstr(expect);
                } else if (type === 'symbol' || isUpper) {
                    ['next'].includes(expect) && (text = 'next');
                    this.getinputstr(text);
                } else {
                    this.pinyinstr += text;
                }
                return;
            }

            if (expect && expect.match(/{.*}\^{.*}/igm)) {
                this.getinputstr(text, view);

                return;
            }
            /* 点击切换符号键盘 */
            if (expect === 'switch') {
                if (this.beforeChangeType('symbol') === false) {
                    return;
                }
                this.prevBoardType.push(this.boardType);
                this.boardType = 'symbol';
                return;
            } else if (expect === 'goback') {
                let t = this.prevBoardType.pop() || 'public';
                if (this.beforeChangeType(t) === false) {
                    return;
                }
                this.boardType = t;
                if (this.boardType === 'public') {
                    this.boardModel = ['chinese', 'text'].includes(this.boardModel) ? this.boardModel : 'chinese';
                }
                this.handWriterStr = '';
                return;
            }
            /* 特殊按键 */
            if (['delete'].includes(expect)) {
                text = expect;
            }

            this.getinputstr(text, view);
        },
        keepPress (e, { expect }) {
            if (this.pattern === 'js') {
                if (this.pinyinstr) {
                    this.timer = setInterval(() => {
                        if (!this.pinyinstr) {
                            this.emitChange('deleteAll');
                            clearInterval(this.timer);
                            this.timer = null;
                            return false;
                        }
                        this.pinyinstr = this.pinyinstr.slice(0, -1);
                    }, 41);
                } else {
                    this.emitChange('deleteAll');
                }
                return;
            }
            let { boardType, pinyinstr, inputarray } = this;
            if (expect === 'delete' && boardType !== 'vertical') {
                // console.log(boardType, pinyinstr, inputarray);
                if (pinyinstr !== '') {
                    this.pinyinstr = '';
                } else {
                    let item = inputarray.find(col => {
                        return col.find(itm => {
                            if (itm.name === 'cursor') {
                                return 1;
                            } else if (['fraction', 'sqrt2', 'sqrt3', 'aimsup', 'aimsub'].includes(itm.name)) {
                                return itm.value.down.find(({ name }) => name === 'cursor') || itm.value.up.find(({ name }) => name === 'cursor');
                            }
                            return 0;
                        });
                    }) || [];
                    item.splice(0, item.length);
                    item.push({
                        name: 'cursor',
                    });
                }
            }
        },
        // 单个拼音转单个汉字，例如输入 'a' 返回 '阿啊呵腌嗄吖锕'
        getSingleHanzi: function (pinyin) {

        },
        // 查找光标
        findcursor: function () {
            // eslint-disable-next-line no-unused-vars
            let pos = { i: -1, j: -1, k: -1, dir: -1 };
            for (let i = 0; i < this.inputarray.length; i++) {
                for (let j = 0; j < this.inputarray[i].length; j++) {
                    if (this.inputarray[i][j].name === 'cursor') {
                        return { i: i, j: j, k: -1, dir: -1 };
                    } else {
                        // 查找公式里的光标
                        if (this.formulaName.includes(this.inputarray[i][j].name)) {
                            let k = this.inputarray[i][j].value.up.findIndex(
                                (value, index, arr) => {
                                    return value.name === 'cursor';
                                }
                            );
                            if (k >= 0) {
                                return { i: i, j: j, k: k, dir: 'up' };
                            } else {
                                let k = this.inputarray[i][j].value.down.findIndex(
                                    (value, index, arr) => {
                                        return value.name === 'cursor';
                                    }
                                );
                                if (k >= 0) {
                                    return { i: i, j: j, k: k, dir: 'down' };
                                }
                            }
                        }
                    }
                }
            }
            return { i: -1, j: -1, k: -1, dir: -1 };
        },
        // 添加光标
        addcursor: function (event, i, j, k, dir, { nextId = this.nextId, symbols = this.symbols } = {}) {
            console.log('addcursor', event, i, j, k, dir, nextId, symbols, this.inputarray);
            let { isCorrect = [] } = this.vthis;
            this.nextId = nextId;
            this.symbols = symbols;
            this.isUpper = false;
            this.boardModel = 'chinese';
            // this.pattern = 'js';
            let pos = this.findcursor();
            // 删除光标
            this.hideFormula();
            if (pos.i >= 0 && pos.j >= 0) {
                if (pos.k === -1) {
                    this.inputarray[pos.i].splice(pos.j, 1);
                } else {
                    this.inputarray[pos.i][pos.j].value[pos.dir].splice(pos.k, 1);
                }
            }
            if (i === -1) {
                // 输入框点击
                this.inputarray[this.inputarray.length - 1].push({
                    name: 'cursor',
                });
            } else {
                if (j === -1) {
                    // 单行点击
                    this.inputarray[i].push({
                        name: 'cursor',
                    });
                } else {
                    if (dir === -1) {
                        // 单个元素点击
                        let aime = event.target;
                        if (pos.i === i && pos.j < j) {
                            j--;
                        }
                        if (event.offsetX < aime.offsetWidth / 2) {
                            this.inputarray[i].splice(j, 0, { name: 'cursor' });
                        } else {
                            this.inputarray[i].splice(j + 1, 0, { name: 'cursor' });
                        }
                    } else {
                        if (k === -1) {
                            // 公式内行点击
                            if (pos.i === i && pos.j < j) {
                                j--;
                            }
                            this.inputarray[i][j].value[dir].push({ name: 'cursor' });
                        } else {
                            // 公式内单个元素点击
                            let aime = event.target;

                            if (pos.i === i && pos.j === j && pos.dir === dir && pos.k < k) {
                                k--;
                            }
                            if (event.offsetX < aime.offsetWidth / 2) {
                                this.inputarray[i][j].value[dir].splice(k, 0, {
                                    name: 'cursor',
                                });
                            } else {
                                this.inputarray[i][j].value[dir].splice(k + 1, 0, {
                                    name: 'cursor',
                                });
                            }
                        }
                    }
                }
            }
            /* 下一空时跳过正确答案 */
            if (isCorrect[i] === '1') {
                this.getinputstr('next');
                return;
            }
            // 滚动条
            this.changemainscroll(event === null ? null : event.target);
        },
        // 删除公式数组里的光标等位置
        deletefraccur: function (frac) {
            let k = frac.findIndex((value, index, arr) => {
                return value.name === 'cursor';
            });
            if (k >= 0) {
                // 删除光标
                frac.splice(k, 1);
            }
            return 0;
        },
        // 删除光标
        removecursor: function (inputarray = this.inputarray) {
            this.isUpper = false;
            this.pinyinstr = '';
            for (let i = 0; i < inputarray.length; i++) {
                for (let j = 0; j < inputarray[i].length; j++) {
                    if (inputarray[i][j].name === 'cursor') {
                        // 删除光标
                        inputarray[i].splice(j, 1);
                        return;
                    } else {
                        // 删除公式里的光标
                        if (
                            inputarray[i][j].name === 'fraction' || inputarray[i][j].name === 'sqrt2' || inputarray[i][j].name === 'sqrt3' || inputarray[i][j].name === 'aimsup' || inputarray[i][j].name === 'aimsub'
                        ) {
                            this.deletefraccur(inputarray[i][j].value.up);
                            this.deletefraccur(inputarray[i][j].value.down);
                        }
                    }
                }
            }
        },
        // 修改滚动条
        changemainscroll: function (target) {
            let vThis = this.vthis;
            if (vThis.rootdata.imshow === 1) {
                vThis.$nextTick(() => {
                    let qtimain = vThis.rootdata.qtimaindiv;
                    if (!qtimain) return;
                    // target没传递的时候取光标元素
                    if (target === undefined || target === null) {
                        if (this.boardType === 'vertical') {
                            target = vThis.$el.querySelector('.numberbox.click');
                        } else {
                            if (this.enterflag === 1) {
                                target = vThis.$el.parentElement.querySelectorAll(
                                    '.qti_fill_input'
                                )[this.i];
                            } else {
                                target = vThis.$el.querySelector('.cursor');
                            }
                        }
                    }

                    if (!target) return;
                    // 绝对定位坐标需要加父元素offsettop
                    // eslint-disable-next-line no-unused-vars
                    let parenttop = 0;
                    // console.log(1111,target)
                    if (target.style.top !== '') {
                        parenttop = target.parentElement.offsetTop;
                    }

                    let targetRect = target.getBoundingClientRect();
                    let qtimainRect = qtimain.getBoundingClientRect();
                    let step = 0;
                    if ((step = targetRect.bottom - qtimainRect.bottom) > 0) {
                        qtimain.scrollTop = qtimain.scrollTop + step + 5;
                    } else if ((step = targetRect.top - qtimainRect.top) < 0) {
                        // 光标位在上面被遮挡滚动条往上滚
                        qtimain.scrollTop = qtimain.scrollTop + step - 5;
                    }
                });
            }
        },
        // 关闭按钮
        closeclick: function (event) {
            this.show = false;
            this.pinyinstr = '';
            this.handWriterStr = '';
            this.hanziarray = [];
            this.candidateShow = false;
            if (this.pattern === 'js') {
                typeof this.jsCallbacks.closed === 'function' && this.jsCallbacks.closed({
                    type: 'closed',
                    event: event,
                });
                this.hideFormula();
                return;
            }

            this.vthis.rootdata.imshow = 0;
            this.removecursor();
            this.hideFormula();
            this.vthis.$nextTick(() => {
                let qtimain = this.vthis.rootdata.qtimaindiv;
                // 关闭输入法时滚动条在最底部就回滚一个像素
                if (qtimain && qtimain.scrollTop + qtimain.offsetHeight >= qtimain.scrollHeight) {
                    qtimain.scrollTop = qtimain.scrollTop - 1;
                }
            });
        },
        // 展开更多待选词
        moreclick () {
            this.candidateShow = true;
        },
        // 判定是否是运算符号
        is_calcsign: function (str) {
            if (str === '+' || str === '-' || str === '×' || str === '÷') {
                return true;
            }
            return false;
        },
        // 插入字符和判断
        insertstr: function (array, index, str, name = 'aime', view) {
            // console.log(str, view);
            let length = array.length;
            let { boardType } = this;
            // 脱式计算需要判断输入
            if (this.type === 2) {
                // 检查前一个元素
                // 小数点前必须是数字
                if (str === '.' && index === 0) {
                    this.$toast('小数点前必须是数字');
                    return;
                }
                if (index > 0) {
                    if (str === '.' && isNaN(array[index - 1].value)) {
                        this.$toast('小数点前必须是数字');
                        return;
                    }
                    if (array[index - 1].name === 'fraction' && !isNaN(str)) {
                        this.$toast('数字前不能是分数');
                        return;
                    }
                    if (
                        this.is_calcsign(array[index - 1].value) && this.is_calcsign(str)
                    ) {
                        this.$toast('运算符号前不能是运算符号');
                        return;
                    }
                }
                if (index + 1 < length) {
                    if (array[index + 1].value === '.' && isNaN(str)) {
                        this.$toast('小数点后必须是数字');
                        return;
                    }
                    if (
                        this.is_calcsign(array[index + 1].value) && this.is_calcsign(str)
                    ) {
                        this.$toast('运算符号前不能是运算符号');
                        return;
                    }
                }
            }

            // console.log("this.i", this.i, "length", this.inputarray[this.i].length,"maxlength",this.maxlength);
            if (this.maxlength) {
                if (this.inputarray[this.i].length > this.maxlength[this.i]) {
                    this.$toast('超过输入长度限制');
                    return;
                }
            }

            array.splice(index, 0, {
                name,
                value: str,
                view,
                class: boardType === 'spell' && 'spell' || '',
            });
        },
        // 查找公式数组里的光标的位置并插入字符
        findfraccurinsert: function (name, str, fracEle, otherEle, view = str, i) {
            // name = 'aime';
            if (str === 'str') return;
            let k = fracEle.findIndex((value, index, arr) => {
                return value.name === 'cursor';
            });
            if (k >= 0) {
                if (
                    this.formulaName.concat(['next']).includes(str)
                ) {
                    if ((str === name && str !== 'sqrt2' && str !== 'sqrt3') || str === 'next') {
                        if (otherEle.length < 1) {
                            fracEle.splice(k, 1);
                            otherEle.push({ name: 'cursor' });
                            return 1;
                        }
                        Bus.toNext(this.vthis, {
                            toNum: i + 1,
                        });
                        return 2;
                    } else {
                        this.$toast('公式里不能插入公式');
                        return 1;
                    }
                } else if (str === 'delete') {
                    if (k > 0) {
                        fracEle.splice(k - 1, 1);
                    }
                } else if (str === 'enter') {
                    if (['comboNumber', 'combo'].includes(this.boardType)) {
                        if (otherEle.length < 1) {
                            fracEle.splice(k, 1);
                            otherEle.push({ name: 'cursor' });
                            return 1;
                        }
                        Bus.toNext(this.vthis, {
                            toNum: i + 1,
                        });
                        return 2;
                    }
                    // 换行标记
                    if (this.enterflag === 0) {
                        this.$toast('公式里不能换行');
                        return 1;
                    } else {
                        if (this.i + 1 < this.inputarray.length) {
                            this.i++;
                            this.addcursor(null, this.i, -1, -1, -1);
                        }
                    }
                } else {
                    if (str === '=') {
                        this.$toast('公式里不允许插入=符号');
                        return 1;
                    }
                    if (str === 'space') {
                        view = str = '';
                        name = 'space';
                    }
                    if (fracEle.length >= 9) {
                        this.$toast('公式里最多8位');
                        return 1;
                    }
                    if (name === 'loop' && fracEle.length > 1) {
                        this.$toast('只能输入一位数字');
                    }
                    this.insertstr(fracEle, k, str, 'aime', view);
                }
            }
            return 0;
        },
        // 从输入法得到输入的字符
        getinputstr: function (str, view = str) {
            if (this.pattern === 'js') {
                this.emitChange(str);
                return;
            }
            let l = this.inputarray.length;
            let jL = null;
            let name = null;
            let temp = null;
            let stop = null;
            let poolArr = this.formulaName;
            for (let i = 0; i < l; i++) {
                jL = this.inputarray[i].length;
                for (let j = 0; j < jL; j++) {
                    temp = this.inputarray[i][j];
                    name = temp.name;
                    if (name === 'cursor') {
                        // 光标位置插入字符
                        if (poolArr.includes(str)) {
                            if (j > 0 && this.inputarray[i][j - 1].name === 'fraction') {
                                if (str === 'fraction') this.$toast('分数前不能是分数');
                                else this.$toast('公式前不能是分数');
                                return;
                            }
                            if (
                                j + 1 < this.inputarray[i].length && this.inputarray[i][j + 1].name === 'fraction'
                            ) {
                                if (str === 'fraction') this.$toast('分数后不能是分数');
                                else this.$toast('公式后不能是分数');
                                return;
                            }
                            if (this.maxlength) {
                                if (this.inputarray[this.i].length > this.maxlength[this.i]) {
                                    this.$toast('超过输入长度限制');
                                    return;
                                }
                            }
                            // 光标位置替换成公式
                            if (str === 'aimsup' || str === 'aimsub') {
                                this.inputarray[i].splice(j, 1, {
                                    name: str,
                                    value: { up: [{ name: 'cursor' }], down: [] },
                                });
                            } else {
                                this.inputarray[i].splice(j, 1, {
                                    name: str,
                                    value: { up: [], down: [{ name: 'cursor' }] },
                                });
                            }
                        } else if (str === 'delete') {
                            if (j === 0) {
                                if (this.boardType !== 'takeOff') {
                                    return;
                                }
                                if (i > 0) {
                                    // 先将这一行的元素移动到上一行
                                    let length = this.inputarray[i].length - j;
                                    for (let k = 0; k < length; k++) {
                                        this.inputarray[i - 1].push(this.inputarray[i].pop());
                                    }
                                    // 再删除这一行
                                    this.inputarray.splice(i, 1);
                                }
                            } else {
                                if (this.boardType === 'vertical') {
                                    this.inputarray.splice(i, 1, [
                                        { name: 'aime', value: '' },
                                        { name: 'cursor' },
                                    ]);
                                } else {
                                    this.inputarray[i].splice(j - 1, 1);
                                }
                            }
                        } else if (str === 'enter') {
                            // 换行标记
                            if (this.enterflag === 0) {
                                // 只有光标的时候不允许换行
                                if (
                                    this.inputarray[i].length === 1 && this.inputarray[i][j].name === 'cursor'
                                ) {
                                    this.$toast('空行不能换行!');
                                    return;
                                }
                                // 先增加一行
                                this.inputarray.splice(i + 1, 0, []);
                                // 再将光标以后的元素挪到下一行
                                let length = this.inputarray[i].length - j;
                                for (let k = 0; k < length; k++) {
                                    this.inputarray[i + 1].unshift(this.inputarray[i].pop());
                                }
                            } else {
                                if (this.vthis.rootdata.bookflag) {
                                    for (let k = this.i + 1; k < this.inputarray.length; k++) {
                                        if (this.vthis.isCorrect[k] === -1) {
                                            this.i = k;
                                            this.addcursor(null, this.i, -1, -1, -1);
                                            break;
                                        }
                                    }
                                } else {
                                    if (this.i + 1 < this.inputarray.length) {
                                        this.i++;
                                        // this.addcursor(null, this.i, -1, -1, -1);
                                        Bus.toNext(this.vthis, {
                                            toNum: this.i,
                                        });
                                    }
                                }
                            }
                        } else if (str === 'space') {
                            this.insertstr(this.inputarray[i], j, ' ', 'space');
                            // this.inputarray[i].splice(j, 0, {name: 'space', value: ""});
                        } else if (str === 'next') {
                            let fisrti = -1;
                            // 最后一空的时候检查前方是否有没有填的空
                            if (i + 1 === this.inputarray.length) {
                                for (let ii = 0; ii < i; ii++) {
                                    if (this.inputarray[ii].length < 1 || this.inputarray[ii][0].value === '') {
                                        fisrti = ii;
                                        break;
                                    }
                                }
                            } else {
                                fisrti = i + 1;
                            }
                            if (fisrti >= 0) {
                                if (this.boardType === 'vertical') {
                                    this.addcursor(null, fisrti, -1, -1, -1);
                                } else {
                                    if (!Bus.toNext(this.vthis, {
                                        toNum: fisrti,
                                    })) { // 没有下一个输入框
                                        // this.show = false;
                                        // this.removecursor();
                                    }
                                }
                            }
                        } else {
                            // 判断是否是竖式题
                            if (this.boardType === 'vertical') {
                                this.inputarray.splice(i, 1, [
                                    { name: 'aime', value: str },
                                    { name: 'cursor' },
                                ]);
                                this.cp_payload.mType * 1 !== 26 && this.getinputstr('next');
                            } else {
                                this.insertstr(this.inputarray[i], j, str, 'aime', view);
                            }
                            // this.inputarray[i].splice(j, 0, { name: 'aime', value: str });
                        }
                        return;
                    } else if (poolArr.includes(name)) {
                        let flag = this.findfraccurinsert(
                            name,
                            str,
                            temp.value.up,
                            temp.value.down,
                            view,
                            i
                        );
                        if (flag === 0) {
                            flag = this.findfraccurinsert(
                                name,
                                str,
                                temp.value.down,
                                temp.value.up,
                                view,
                                i
                            );
                        }
                        if (flag === 2) {
                            stop = true;
                        }
                    }
                }
                if (stop) break;
            }
        },
        /* 调整界面到合适位置 */
        moveSight (e) {
            this.$nextTick(() => {
                let app = document.getElementById('app');
                let { $el } = this;
                let $elRect = $el.getBoundingClientRect();

                if (this.show) {
                    let cursor = document.getElementsByClassName('k-board cursor')[0];
                    if (!cursor) return;
                    let curRect = cursor.getBoundingClientRect();
                    let differ = $elRect.top - curRect.bottom;
                    let appTop = document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset;
                    let endTop = appTop;
                    // setCss.call(app, {
                    //   marginBottom: $elRect.height + 'px',
                    // });

                    if (differ < 0) { // 光标低于键盘时
                        endTop = appTop - differ + 15;
                    } else if (curRect.top < 0) { // 光标高于屏幕
                        endTop = appTop + curRect.top - 20;
                    }

                    scrollTo((endTop - appTop) / 200 * 16, appTop, endTop);
                } else {
                    setCss.call(app, {
                        marginBottom: '0px',
                    });
                }
            });
        },
        emitChange (res) {
            typeof this.jsCallbacks.change === 'function' && this.jsCallbacks.change(res);
        },
        // 键盘挂载到指定节点后的回调函数
        mountedCallback () {
            document.querySelector(this.el).addEventListener('scroll', (e) => {
                console.log(e.target);
            }, false);
        },
        /* 显示公式输入区 */
        showFormula (name, text) {
            let up = [];
            let down = [];
            // this.disableBtnMap = ['fraction', 'enter', 'space', 'sqrt2', 'sqrt3', 'aimsup', 'aimsub', 'σ^2', 'loop'];
            if (this.formulaReg.show && this.formulaReg.data.name === name) {
                this.hideFormula();
                return;
            }
            // 光标位置替换成公式
            if (name === 'aimsup' || name === 'aimsub') {
                up = [{ name: 'cursor' }];
            } else {
                down = [{ name: 'cursor' }];
            }
            Object.assign(this.formulaReg, {
                show: true,
                data: {
                    name,
                    value: { up, down, mixed: [] },
                },
                text,
            });
            document.body.appendChild(this.$refs.mirror);
        },
        /* 隐藏公式输入区 */
        hideFormula (name) {
            // this.disableBtnMap = [];
            Object.assign(this.formulaReg, {
                show: false,
                data: {
                    name,
                    value: { up: [], down: [], mixed: [] },
                },
            });
        },
        /* 符号区输入 */
        inputFormula (text) {
            let value = this.formulaReg.data.value;
            let arr = Object.entries(value).find(([k, v]) => {
                return v.find(k => k.name === 'cursor');
            });
            if (arr) {
                if (text === 'next') {
                    if (['sqrt2', 'loop'].includes(this.formulaReg.data.name)) {
                        return;
                    } else if (['fraction'].includes(this.formulaReg.data.name)) {
                        this.formulaClick({ site: {
                            mixed: 'down',
                            up: 'mixed',
                            down: 'up',
                        }[arr[0]] });
                        return;
                    }
                    this.formulaClick({ site: arr[0] === 'up' ? 'down' : 'up' });
                    return;
                } else if (text === 'delete') {
                    let l = arr[1].length,
                        i = arr[1].findIndex((v, idx, s) => s[l - idx - 1].name !== 'cursor');
                    if (i > -1 && l > 0) {
                        arr[1].splice(l - 1 - i, 1);
                    }
                    return;
                } else if (text === 'goback') {
                    this.boardModel = ['chinese', 'text'].includes(this.boardModel) ? this.boardModel : 'chinese';
                    this.hideFormula();
                    return;
                }
                let i = arr[1].findIndex(a => a.name !== 'cursor');
                if (!_onlyNumber(text)) return;
                if (this.formulaReg.data.name === 'loop' && i > -1) {
                    arr[1].splice(i, 1, {
                        name: 'aime',
                        value: text,
                        view: text,
                        class: this.boardType === 'spell' && 'spell' || '',
                    });
                } else {
                    if (arr[1].length > 5) return;
                    arr[1].push({
                        name: 'aime',
                        value: text,
                        view: text,
                        class: this.boardType === 'spell' && 'spell' || '',
                    });
                }
            }
        },
        /* 点击符号区 */
        formulaClick ({ idx, site }) {
            if (site === -1) return;
            let value = this.formulaReg.data.value;
            Object.entries(value).forEach(([k, v]) => {
                let i = v.findIndex(k => k.name === 'cursor');
                i > -1 && v.splice(i, 1);
            });
            value[site].push({ name: 'cursor' });
        },
        /* 确认符号输入 */
        confirmFormula () {
            let isConfirm = false;
            let formulaRegData = this.formulaReg.data.value;
            let formulaName = this.formulaReg.data.name;
            let isExistUp = formulaRegData && formulaRegData.up.some(item => item.value !== '' && item.value !== undefined && item.value !== null);
            let isExistDown = formulaRegData && formulaRegData.down.some(item => item.value !== '' && item.value !== undefined && item.value !== null);
            if (formulaName === 'sqrt2' || formulaName === 'loop') { // 单空
                if (isExistDown) {
                    isConfirm = true;
                }
            } else { // 两个空
                if (isExistUp && isExistDown) {
                    isConfirm = true;
                }
            }
            if (isConfirm) {
                let self = this;
                self.inputarray.every(row => {
                    return row.every((item, idx) => {
                        let res = item.name === 'cursor';
                        Object.entries(self.formulaReg.data.value).forEach(([k, v]) => {
                            let i = v.findIndex(k => k.name === 'cursor');
                            i > -1 && v.splice(i, 1);
                        });
                        if (res) {
                            row.splice(idx, 0, {
                                name: self.formulaReg.data.name,
                                value: self.formulaReg.data.value,
                            });
                        }
                        return !res;
                    });
                });
                let data = this.formulaReg.data,
                    text = this.formulaReg.text,
                    res = '';
                console.log(data.name, self.cp_mirror.data);
                switch (data.name) {
                    case 'fraction': {
                        console.log(text);
                        res = text.replace('\\S*', self.cp_mirror.data.mixed);
                        res = res.replace('\\S*', self.cp_mirror.data.up);
                        res = res.replace('\\S*', self.cp_mirror.data.down);
                    }
                        break;
                    case 'sqrt2': {
                        res = text.replace('\\S*', self.cp_mirror.data.down);
                    }
                        break;
                    case 'aimsup': {
                        res = text.replace('\\S*', self.cp_mirror.data.up);
                        res = res.replace('\\S*', self.cp_mirror.data.down);
                    }
                        break;
                    case 'aimsub': {
                        res = text.replace('\\S*', self.cp_mirror.data.up);
                        res = res.replace('\\S*', self.cp_mirror.data.down);
                    }
                        break;
                    case 'loop': {
                        res = text.replace('\\S*', self.cp_mirror.data.down);
                    }
                        break;
                }

                html2canvas(self.$refs.mirror, {
                    backgroundColor: null,
                }).then((canvas) => {
                    let picData = canvas.toDataURL();
                    if (self.pattern === 'js') {
                        self.emitChange({
                            picData,
                            text: res,
                            type: self.cp_mirror.name,
                        });
                    }
                    document.body.removeChild(self.$refs.mirror);
                    self.hideFormula();
                });
            }
        },
        /* 计算字体大小 */
        calcFontSize () {
            let width = this.$el.offsetWidth,
                height = this.$el.offsetHeight,
                fontSize = '12px',
                sHeight = window.screen.height;
            if (width < 400) {
                fontSize = sHeight * 0.03;
            } else if (width < 600) {
                fontSize = Math.min(width * 0.04, 20, height / 11);
            } else if (width < 1000) {
                fontSize = Math.min(20, height / 11);
            } else if (width > 1000) {
                fontSize = Math.min(24, height / 11);
            }
            Object.assign(this.boardStyle, {
                fontSize: fontSize + 'px',
            });
        },

        /* 上传图片sourceSelectorSuc */
        sourceSelectorSuc (p) {
            this.emitChange({
                data: p,
                type: 'uploadImage',
            });
        },
        getException (p) {
        },
        /* 键盘类型切换的回调 */
        beforeChangeType (p) {
            let boardModel = this.boardModel;
            if (p === 'public') {
                boardModel = ['chinese', 'text'].includes(this.boardModel) ? boardModel : 'chinese';
            }
            return this.jsCallbacks.beforeChangeType(p, {
                boardType: p,
                boardModel,
            });
        },
        onModel ({ boardModel }) {
            this.jsCallbacks.beforeChangeType('symbol', {
                boardType: 'symbol',
                boardModel: boardModel,
            });
        },
    },
};

function setCss (obj) {
    Object.entries(obj).forEach(([k, val]) => {
        this.style[k] = val;
    });
}

function scrollTo (step, appTop, endTop) {
    if (step !== 0) {
        let t = appTop + step;
        if ((step > 0 && t > endTop) || (step < 0 && t < endTop)) {
            t = endTop;
        } else {
            setTimeout(() => {
                scrollTo(step, t, endTop);
            }, 20);
        }
        document.body.scrollTop = t;
        document.documentElement.scrollTop = t;
    }
}
</script>

<style lang='scss' scoped>

  .linpeng-key-board-div {
    font-family: "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", "宋体";
    box-sizing: border-box;
    color: #283357;
    display: block;
    -webkit-user-select: none;
    user-select: none;
    width: 100%;
    height: 45%;
    /*min-height: 300px;*/
    /*max-height: 300px;*/
    position: absolute;
    z-index: 4000;
    bottom: 0px;
    right: 0px;
    font-size: 4vh;
    background: #fff;
    text-align: center;
    &.pad {
      width: calc(100% - 24vh);
      margin-right: 24vh;
    }
    &.book_pad {
      width: calc(100% - 24vh);
      margin-right: 12vh;
      margin-left: 12vh;
      bottom: 8vh;
    }
    &.phone {
      bottom: 8vh;
      height: 37%;
    }
    .k-symbol {
      font-size: 80%;
    }
  }

  .k-btn-wrap {
    height: 85%;
    background-color: #f7f6fb;
  }

  .cp_candidate_wrapper {
    // padding: 10px;
    height: 85%;
    position: relative;
    top: -85%;
    background-color: #fff;
    .k-btn-wrap {
      padding: 0;
    }
  }

  .aimtooldiv {
    position: relative;
    height: 15%;
    background: #efefef;
    font-family: 'customFont', 'customFont1', 'customFont2', "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", 'spe-symbol';
    .input-type-choice {
      position: absolute;
      height: 100%;
      display: flex;
      align-items: center;
      span {
        height: 60%;
        width: 32px;
        margin-left: 25px;
        &.keyboard {
          background: url(./images/keyboard.png) no-repeat center center;
          background-size: contain;
          &.active {
            background: url(./images/keyboard_active.png) no-repeat center center;
            background-size: contain;
          }
        }
        &.writeboard {
          background: url(./images/writeboard.png) no-repeat center center;
          background-size: contain;
          &.active {
            background: url(./images/writeboard_active.png) no-repeat center center;
            background-size: contain;
          }
        }
        &.HandPaintImg {
          background: url(./images/HandPaintImg.png) no-repeat center center;
          background-size: contain;
        }
        &.choosePhoto {
          background: url(./images/choosePhoto.png) no-repeat center center;
          background-size: contain;
        }
        &.audio {
          background: url(./images/audio.png) no-repeat center center;
          background-size: contain;
        }
      }
    }
    .hiddth-scroll {
      height: 100%;
      // overflow: hidden;
      width: calc(100% - 50px);
    }
    .aimresultdiv {
      height: 100%;
      &.mobile {
        height: calc(100% + 20px);
      }
    }
    .aimclosediv {
      width: 50px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 4vh;
      background: url("./images/down.png") no-repeat center center;
      background-size: auto 20%;
    }
    .aimmorediv {
      width: 50px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 4vh;
      border-left: 1px solid #bec7cc;
      background: url("./images/more.png") no-repeat center center;
    }

    .k-candidate {
      position: absolute;
      bottom: calc(100% + 1px);
      left: 0;
      padding: 0 10px;
      height: 60%;
      font-size: 16px;
      background: rgba(19, 208, 152, .85);
      color: #fff;
      display: flex;
      align-items: center;
    }
  }

  .aimresultdiv {
    .result {
      padding: 0 5px;
      height: 100%;
      color: #283357;
      display: flex;
      align-items: center;
      &.mobile {
        height: calc(100% - 20px);
      }
      .result-li {
        height: 60%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-right: 2px solid #bec7cc;
        .result-span {
          width: 60px;
          height: 40px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
        }
        &:active {
          .result-span {
            color: #fff;
            background-color: #4ad8ae;
          }
          color: #fff;
        }
        &:last-child {
          border-right: none;
        }
      }
    }
  }
</style>

<style lang="scss">
  $interval: 8px; // 横向间隔
  $vertical: 8px; // 纵向间隔
  $trans: all .1s;
  $shadow: 0 3px 4px 0px rgba(85, 85, 85, 0.15); // 数字阴影
  $symbol-shadow: 0 3px 4px 0px rgba(85, 85, 85, 0.15); // 字符阴影

  $color: #858788;

  .clear-fix {
    &:before, &:after {
      content: '';
      display: table;
    }
    &:after {
      clear: both;
    }
  }

  .fl {
    float: left;
  }

  .fr {
    float: right;
  }

  /**/
  .linpeng-key-board-div {
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    ul, li {
      list-style: none;
    }
  }

  /*引入特殊符号转字体图标*/
  @font-face {
    font-family: 'spe-symbol';  /* project id 780790 */
    /*src: url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.eot'),*/
    /*url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.eot?#iefix') format('embedded-opentype');*/
    src: url('./fonts/symbol/iconfont.woff') format('woff'),
    url('./fonts/symbol/iconfont.ttf') format('truetype');
    /*url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.svg#spe-symbol') format('svg');*/
  }

  .k-btn-wrap {
    padding: $interval / 2 $interval $interval $interval;
    .k-row {
      & + .k-row {
        margin-top: $vertical;
      }
      &.k-row-2 {
        height: calc((100% - #{$vertical} * 1) / 2);
      }
      &.k-row-3 {
        height: calc((100% - #{$vertical} * 2) / 3);
      }
      &.k-row-4 {
        height: calc((100% - #{$vertical} * 3) / 4);
      }
      &.k-row-5 {
        height: calc((100% - #{$vertical} * 4) / 5);
      }
    }

    .k-btn {
      border-radius: 8px;
      background: #fff;
      box-shadow: $shadow;
      height: 100%;
      white-space: nowrap;
      -webkit-transform: $trans;
      -moz-transform: $trans;
      -ms-transform: $trans;
      -o-transform: $trans;
      transform: $trans;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .k-btn-bg {
        width: 80%;
        height: 80%;
        position: absolute;
        top: 10%;
        left: 10%;
        display: inline-block;
        background-color: #transparent;
      }
      & + .k-btn {
        margin-left: $interval;
      }
      &.enter {
        background: url("images/enter_pc.png") no-repeat scroll center center #e8ebee;
        font-size: 0;
      }
      &.fraction {
        font-size: 0;
        .k-btn-bg {
          background: url("images/fraction_pc.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.caseswitch {
        background: url("images/small_w.png") no-repeat scroll center center #e8ebee;
        background-size: 30% auto;
        &.switchcase {
          background: url("images/big_w.png") no-repeat scroll center center #e8ebee;
        }
        font-size: 0;
      }
      &.k-space {
        background-color: #fff;
        // background: url("images/space_pc.png") no-repeat scroll center center #e8ebee;
        // font-size: 0;
      }
      &.sqrt2 {
        font-size: 0;
        .k-btn-bg {
          background: url("images/sqrt2.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.sqrt3 {
        background: url("images/sqrt3.png") no-repeat scroll center center #e8ebee;
        font-size: 0;
      }
      &.delete {
        /*background-size: 4vw;*/
        /*object-fit: contain;*/
        font-size: 0;
        .k-btn-bg {
          width: 30%;
          height: 50%;
          top: 25%;
          left: 35%;
          background: url("images/delete.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
        &.active {
          background-color: #13d098;
          .k-btn-bg {
            background: url("images/delete_a.png") no-repeat scroll center center #e7ebee;
            background-size: contain;
            background-color: #13d098;
          }
        }
      }
      &.remainder {
        font-size: 0;
        .k-btn-bg {
          background: url("images/remainder.png") no-repeat scroll center center transparent;
          background-size: contain;
          height: 70%;
          top: 15%;
        }
      }
      &.aimsup {
        font-size: 0;
        .k-btn-bg {
          background: url("images/aimsup.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.aimsub {
        font-size: 0;
        .k-btn-bg {
          background: url("images/aimsub.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.monospace {
        font-family: monospace, Symbola, "Times New Roman", serif;
        /*font-size: 200%;*/
      }
      &.middle {
        font-size: 75%;
      }
      &.k-disable {
        color: #aaa;
        cursor: not-allowed;
        background: #eff2f5;
      }
      &.loop {
        font-size: 0;
        .k-btn-bg {
          background: url("images/loop.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.angle {
        font-size: 0;
        .k-btn-bg {
          background: url("images/angle.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }
      &.divide {
        font-size: 0;
        .k-btn-bg {
          background: url("images/divide.png") no-repeat scroll center center transparent;
          background-size: contain;
        }
      }

      /*&:active {*/
      /*background-color: #13d098;*/
      /*}*/
      &.active {
        background-color: #13d098;
        color: #fff;
      }
      &.k-symbol.small {
        font-size: 80%;
      }
      &.disable {
        opacity: .5;
        color: #b8bdc8;
        pointer-events: none;
      }

    }

    .k-symbol {
      background-size: 6vw;
    }

    .k-btn.bold {
      font-weight: 600;
    }

    @for $i from 3 through 10 {
      .k-btn-#{$i} {
        width: calc((100% - #{$interval} * #{$i - 1}) / #{$i});
      }
    }

    .k-btn-5.double {
      width: calc((200% - #{$interval} * 3) / 5);
    }
    .k-btn-6.double {
      width: calc((100% - #{$interval} * 5) / 3 + #{$interval});
    }
    .k-btn-7.double {
      width: calc((100% - #{$interval} * 6) / 3.5 + #{$interval});
    }

    .k-symbol, .k-space, .k-next {
      // font-family: "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", 'spe-symbol', '宋体';
      font-family: 'customFont1', 'customFont2', "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", 'spe-symbol';
      background-color: #e8ebee;
      box-shadow: $symbol-shadow;
    }

    .k-delete {
      height: 50%;
    }

    .k-hidden {
      display: none;
    }

    .sym-pad {
      padding-left: $interval;
      font-size: .8em;
    }

    .sy-ul.num-ul {
      padding-left: #{$interval * .5};
      // padding-right: #{$interval + 10};
    }

    .nav-ul.num-ul {
      // padding-right: #{$interval + 10};
    }
  }

  .k-letters {
    .k-btn-6 {
      width: calc((100% - #{$interval} * 9) / 10 + #{$interval});
    }
    .k-btn-6 + .k-space, .k-btn-6 + .k-next {
      width: calc(50% - ((100% - #{$interval} * 9) / 5 + #{$interval} * 4.5));
    }
    .k-btn-7 {
      width: calc((100% - #{$interval} * 6) / 10)
    }
    .k-btn-7 + .k-space {
      width: calc((100% - #{$interval} * 6) / 10 * 3)
    }
    .k-btn-7 + .k-next {
      width: calc((100% - #{$interval} * 6) / 10 * 2)
    }
    .k-btn-10, .k-btn-9, .k-btn-8 {
      width: calc((100% - #{$interval} * 9) / 10);
    }
    .k-btn-8 + .k-space, .k-btn-8 + .k-next {
      width: calc((100% - #{$interval} * 4) / 5);
    }
    .k-btn-9:first-child {
      margin-left: calc((100% - #{$interval} * 9) / 20 + #{$interval} * .5);
    }
    .k-btn-8:first-child {
      /*margin-left: calc((100% - #{$interval} * 9) / 10 + #{$interval})*/;
    }
    .k-btn-9.k-symbol {
      width: calc((100% - #{$interval} * 9) / 8.5 + #{$interval});
    }
    .k-btn-9.k-symbol:first-child {
      margin-left: calc((100% - #{$interval} * 9) / 20 - #{$interval});
    }
  }

  /*拼音键盘*/
  .wrap-spell {
    .spell {
      position: relative;
      &:before {
        content: '';
        display: table;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background: #666;
        position: absolute;
        top: 15%;
        right: 15%;
      }
    }

    .k-btn-8:first-child {
      margin-left: calc((100% - #{$interval} * 9) / 10 + #{$interval} * .5);
    }

    .k-row-4 {
      display: flex;
      &:last-of-type {
        .k-symbol {
          flex-basis: calc((100% - #{$interval} * 9) / 10);
        }

        .k-space {
          flex-grow: 1;
        }

        .k-next {
          flex-basis: calc((300% - #{$interval} * 17) / 20);
        }
      }
    }
  }

  /*手机端*/
  @media screen and (max-width: 600px) {
    $interval: 8px; // 横向间隔
    $vertical: 1.4vh; // 纵向间隔

    .k-btn-wrap {
      /*font-size: 4vw;*/
      .k-row {
        & + .k-row {
          margin-top: $vertical;
        }
        &.k-row-2 {
          height: calc((100% - #{$vertical} * 1) / 2);
        }
        &.k-row-3 {
          height: calc((100% - #{$vertical} * 2) / 3);
        }
        &.k-row-4 {
          height: calc((100% - #{$vertical} * 3) / 4);
        }
        &.k-row-5 {
          height: calc((100% - #{$vertical} * 4) / 5);
        }

      }

      .k-btn {
        border-radius: 6px;
        box-shadow: $shadow;
        & + .k-btn {
          margin-left: $interval;
        }
      }
      @for $i from 3 through 10 {
        .k-btn-#{$i} {
          width: calc((100% - #{$interval} * #{$i - 1}) / #{$i});
        }
      }
      .k-btn-5.double {
        width: calc((200% - #{$interval} * 3) / 5);
      }
      .k-btn-6.double {
        width: calc((100% - #{$interval} * 5) / 3 + #{$interval});
      }
      .k-btn-7.double {
        width: calc((100% - #{$interval} * 6) / 3.5 + #{$interval});
      }
      .sym-pad {
        padding-left: $interval;
      }

      .sy-ul.num-ul {
        padding-right: #{$interval + 16};
        padding-left: $interval;
      }

      .nav-ul.num-ul {
        padding-right: #{$interval + 16};
      }
    }

    .k-letters {
      .k-btn-6 {
        width: calc((100% - #{$interval} * 9) / 10 + #{$interval});
      }
      .k-btn-6 + .k-space, .k-btn-6 + .k-next {
        width: calc(50% - ((100% - #{$interval} * 9) / 5 + #{$interval} * 4.5));
      }
      .k-btn-7 {
        width: calc((100% - #{$interval} * 4) / 8)
      }
      .k-btn-7 + .k-space {
        width: calc((100% - #{$interval} * 4) / 8)
      }
      .k-btn-7 + .k-next {
        width: calc((100% - #{$interval} * 4) / 8 * 1.5)
      }
      .k-btn-10, .k-btn-9, .k-btn-8 {
        width: calc((100% - #{$interval} * 9) / 10);
      }
      .k-btn-9:first-child {
        margin-left: calc((100% - #{$interval} * 9) / 20 + #{$interval} * .5);
      }
      .k-btn-8:first-child {
        margin-left: calc((100% - #{$interval} * 9) / 10 + #{$interval});
      }
      .k-btn-9.k-symbol, .k-btn-8.k-symbol {
        width: calc((100% - #{$interval} * 9) / 10 + #{$interval});
      }
      .k-btn-9.k-symbol:first-child {
        margin-left: calc((100% - #{$interval} * 9) / 20 - #{$interval} * .5);
      }
    }

    .wrap-spell {
      .spell {
        position: relative;
        &:before {
          content: '';
          display: table;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: #666;
          position: absolute;
          top: 15%;
          right: 15%;
        }
      }

      .k-btn-8:first-child {
        margin-left: calc((100% - #{$interval} * 4) / 10);
      }

      .k-row-4 {
        display: flex;
        &:last-of-type {
          .k-symbol {
            flex-basis: calc((100% - #{$interval} * 9) / 10);
          }

          .k-space {
            flex-grow: 1;
          }

          .k-next {
            flex-basis: calc((200% - #{$interval} * 3) / 10);
          }
        }
      }
    }

    .k-symbol, .k-space, .k-next {
      font-size: 85%;
    }
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s;
  }

  .fade-enter, .fade-leave-to {
    opacity: 0;
  }

  .im-trans {
    -webkit-transition: all .2s ease-in;
    -moz-transition: all .2s ease-in;
    -ms-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    transition: all .2s ease-in;
  }

  .im-choice {
    position: fixed;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    width: 100%;
    background: #e8ebee;
    padding: 2vw;
  }

  .im-tabs {
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 40vh;
    position: relative;
    margin-bottom: -30px;
    padding-bottom: 30px;
    background: #e8ebee;
    ul {
      padding: 0;
      margin: 0;
      margin-bottom: -2vw;
      margin-right: -2vw;
      width: calc(100% + 2vw);

    }
    li {
      list-style: none;
    }
    .im-item {
      span {
        display: inline-block;
        background: #fff;
        border: 1px solid $color;
        border-radius: 8px;
        margin-right: 2vw;
        margin-bottom: 2vw;
        word-break: break-word;
        overflow: hidden;
        font-family: monospace, Symbola, "Times New Roman", serif;
      }

      .im-span-txt {
        padding: 8px;
      }
    }

    @media screen and (min-width: 400px) {
      .im-item .im-span-txt {
        padding: 10px;
      }
    }

    @media screen and (min-width: 600px) {
      .im-item .im-span-txt {
        padding: 12px 14px;
      }
    }
  }

  .mirror {
    position: absolute;
    z-index: -1;
  }

  .im-close {
    box-sizing: border-box;
    position: absolute;
    width: 35%;
    height: 30px;
    padding: 5px 0;
    bottom: 100%;
    margin-bottom: -5px;
    left: 32.5%;
    span {
      background: #e8ebee;
      display: block;
      width: 100%;
      height: 100%;
      border-top-right-radius: 30px;
      border-top-left-radius: 30px;
      &:before {
        content: '';
        display: table;
        border: 2px solid {
          color: transparent;
          left-color: $color;
          bottom-color: $color;
        }
      ;
        width: 10px;
        height: 10px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -7px;
        margin-top: -7px;
        -webkit-transform: rotate3d(0, 0, 1, -45deg);
        -moz-transform: rotate3d(0, 0, 1, -45deg);
        -ms-transform: rotate3d(0, 0, 1, -45deg);
        -o-transform: rotate3d(0, 0, 1, -45deg);
        transform: rotate3d(0, 0, 1, -45deg);
      }
    }
  }

  .im-choice-img {
    max-width: calc(96vw - 2px);
  }

  .formula-reg.formula {
    position: absolute;
    bottom: 100%;
    width: 100%;
    padding: 15px 0;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #EFEFEF;
    .formula-wrap {
      min-width: 12vw;
      max-width: 80vw;
    }

    .formula-btn {
      margin-left: 6vw;
      background-color: #e8ebee;
      border-radius: 6px;
      padding: 1vw 2vw;
      font-size: 0.8em;
      &:active {
        background-color: #13d098;
        color: #fff;
      }
      &.disabled {
        background-color: #e8ebee;
        color: #fff;
      }
    }
  }

  .formula-mirror.formula {
    position: fixed;
    z-index: -9991;
    background: rgba(0, 0, 0, 0);
    top: 0px;
    left: 100px;
    padding: 0 4px;
    .enterdiv {
      background-color: transparent;
      min-width: 10px;
      min-height: 0;
      height: 3.5vh;
      border: none;
    }
    .fraction {
      .fraction-line {
        margin: 0;
        border: 1px solid #283357;
      }
      .formula-wrap {
        &.fraction {
          background: transparent;
        }
        &.sqrt2 {
          margin-top: 1px;
          .down {
            border-top-width: 2px;
          }
        }
      }
      .mixed {
        margin-right: 0;
        min-width: 0;
      }
    }

    .sqrt2 {
      padding-left: 2vh;
      .formula-content {

        border-top-width: 2px;
        padding: 6px 4px;
        height: 5vh;
      }
    }

    .aimsup {
      .formula-content {
        padding-top: 2vh;
      }
      .down {
        top: -1.5vh;
        margin-left: 0;
      }
      .up {
        min-width: 0;
      }
    }

    .aimsub {
      .formula-content {
        padding-bottom: 2vh;
      }
      .down {
        bottom: -1.5vh;
        margin-left: 0;
      }
      .up {
        min-width: 0;
      }
    }

    .loop {
      .formula-content {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .fraction-line {
        width: 3px;
        margin: 0 0 4px 0;
      }
      .down {
        min-width: 0;
      }
    }
  }
</style>
